<script setup>
import {reactive, onMounted, getCurrentInstance, defineProps, ref, watch, watchEffect, onUpdated, nextTick} from "vue";
// import Sortable from "sortablejs";
import Sortable from "sortablejs";
import {keys} from "lodash-unified";
import RowPhraseWordSubTable from "@/components/RowPhraseWordSubTable.vue";
import RowPhraseWordSubTables from "@/components/RowPhraseWordSubTables.vue";
import {InfoFilled, Plus} from "@element-plus/icons-vue";
import '@fortawesome/fontawesome-free/css/all.css';
import DraggableTest2 from "@/testCompGroupC/subTest/DraggableTest2.vue";
import $ from "jquery"
import {clearAndPushAll} from "@/utils/ArrayUtil";

let props = defineProps(["conceptsPopOverTempVisible","gridData"])



let theRowSortable;
const rowDrop = () => {
  // console.log("rowdrop");
  const instance = getCurrentInstance();
  // const tbody = document.querySelector('.compactPopover .el-table__body-wrapper tbody');
  const tbody = instance?.ctx?.$el?.parentNode.querySelector(".el-table__body-wrapper tbody");
  theRowSortable = Sortable.create(tbody, {
    draggable: ".compactPopover .el-table__row",
    dataIdAttr: "short",
    animation: 250,
    onEnd(evt) {
      console.log("row dragged");
      const currRow = props.gridData.splice(evt.oldIndex, 1)[0];
      props.gridData.splice(evt.newIndex, 0, currRow);
      nextTick(()=>{
          let rows = $(theTable?.value?.$el.querySelector("tbody")).children(".el-table__row");
          console.log("rows:",rows);

          for (const row of rows) {
              row?.setAttribute("short", row.__vnode.key);
          }

          let shorts = props.gridData.map(ele => ele.short).join("\n");
          console.log("shorts",shorts);
          let showing = theRowSortable.toArray().join("\n");
          console.log("showing",showing);
          if (showing !== shorts) {
              theRowSortable.sort(props.gridData.map(ele => ele.short), false);
          }
      });
      console.log(props.gridData);
    }
  });

  theRowSortable.options.disabled = true;
  // theRowSortable.options.disabled = true;
  console.log("theSortable,", theRowSortable.toArray());
}
// 列拖拽
const columnDrop = () => {
  const instance = getCurrentInstance();
  const tr = instance?.ctx?.$el?.parentNode.querySelector(".el-table__header-wrapper tr");
  // Sortable.create(tr, {
  //     animation: 150,
  //     delay: 0,
  //     onEnd: (evt) => {
  //         // const oldItem = columnList.value[evt.oldIndex];
  //         // columnList.value.splice(evt.oldIndex, 1);
  //         // columnList.value.splice(evt.newIndex, 0, oldItem);
  //         // console.log(columnList.value);
  //     }
  // });
}

function indexing(idx) {
  console.log("indexing the,", idx);
  return idx;
}

function testchange() {
  const currRow = props.gridData.splice(0, 1)[0];
  props.gridData.splice(1, 0, currRow);
  console.log(props.gridData);
}

let rateChangeObjRef = ref({});
let allSortableSw = ref(false);
let allSortableSwDisabled = ref(false);
let theTable = ref();
let column1Ref = ref();
let column2Ref = ref();

let rateTexts = ['瞄一眼', '随便看看', '普通', '次重要', '重要'];

function onSortChanged(sortingColumnInfoProxy, bb, cc, dd, ee) {

  // console.log("onSortChanged",aa,bb,cc,dd,ee,keys(rateChangeObjRef.value));
  // rateChangeObjRef.value = sortingColumnInfoProxy;

    if(sortingColumnInfoProxy.order){
        allSortableSw.value = false;
    }
  // if (aa.order) {
  //     theRowSortable.options.disabled = true;
  // } else {
  //     theRowSortable.options.disabled = false;
  // }
}

let expandedRowKeys = reactive([]);
let toExpandedRowKeys = reactive(['']);
function onExpandChange(currExpandChangingRowData, stayExpandedRowsDatas) {
    // clearAndPushAll(expandedRowKeys,[...stayExpandedRowsDatas.map(ele=>ele.short)]);
    if(stayExpandedRowsDatas.length>0) {
        // theRowSortable.options.disabled = true;
        allSortableSw.value = false;
    }
    // }else{
    //     // theRowSortable.options.disabled = false;
    // }

  // console.log("onExpandChange:", currExpandChangingRowData, stayExpandedRowsDatas);
  console.log("columns info", column1Ref.value, column2Ref.value)
}

function rowClassNameIt(aa, bb, cc, dd, ee, ff) {
  // getCurrentInstance()
  // console.log("rowClassNameIt:",aa,bb,cc,dd,ee,ff);
  //   console.log("theTable:",$(theTable?.value?.$el));
  // console.log("theTable .el-table__row:",theTable?.value?.$el?.querySelectorAll(" tbody:first-of-type>.el-table__row"));
  // console.log("theTable:",theTable?.value?.$el?.querySelectorAll(".el-table__row")[aa.rowIndex]);

    // console.log("rowClassNameIt:",$(theTable?.value?.$el.querySelector("tbody")).children(".el-table__row")[aa.rowIndex]?.setAttribute);
    $(theTable?.value?.$el.querySelector("tbody")).children(".el-table__row")[aa.rowIndex]?.setAttribute("short", aa?.row?.short)
  // console.log("theTable:",theTable?.value);
  return "";
}

// watchEffect(() => {
//     console.log("expandedRowKeys changed",expandedRowKeys);
//     let aa = expandedRowKeys[0];
//       // if(aa){
//       //
//       // }
// })
// watchEffect(() => {
//     // console.log("rateChangeObjRef.value : and allSortableSw.value",rateChangeObjRef.value,allSortableSw.value)
//
//     // console.log("watched effect 1");
//     rateChangeObjRef.value;
//     let aa = expandedRowKeys[0];
//
//     if (!theRowSortable) {
//         return;
//     }
//     // if (!allSortableSw.value) {
//     //     allSortableSwDisabled.value = true;
//     //   // theRowSortable.options.disabled = true;
//     // } else
//     if (rateChangeObjRef.value.order) {
//         allSortableSwDisabled.value = true;
//         // theRowSortable.options.disabled = true;
//     } else if (expandedRowKeys.length > 0) {
//         allSortableSwDisabled.value = true;
//         // theRowSortable.options.disabled = true;
//     } else {
//         allSortableSwDisabled.value = false;
//         // theRowSortable.options.disabled = false;
//     }
// })

watch(allSortableSw,newVal=>{
    // console.log("allSortableSw",newVal);
    if(newVal){
        props.gridData.forEach((rowData)=>{
            theTable.value.toggleRowExpansion(rowData,false);
        });
        // clearAndPushAll(toExpandedRowKeys,[]);
        theTable.value.clearSort();
        theRowSortable.options.disabled = false;
    }else {

        theRowSortable.options.disabled = true;
    }
})

onMounted(() => {
  // console.log("DraggableElTable.vue mounted");
  const instance = getCurrentInstance();
  console.log("the instance,", instance)
  rowDrop();
  columnDrop();
})

// onUpdated(() => {
//   console.log("DraggableElTable.vue updated");
// })

</script>

<template>
  <div class="drtable">
    <!--    {{gridData}}-->
    <!--    <el-table :data="gridData" :width="500" :border="false" row-key="id">-->
    <!--        default-expand-all-->
    <!--        :table-layout="`fixed`"-->
<!--      row-key="id"-->
<!--      <div @click="toExpandedRowKeys.push('zn')">{{toExpandedRowKeys}}</div>-->
<!--      <div @click="clearAndPushAll(toExpandedRowKeys,[])">{{toExpandedRowKeys}}</div>-->
<!--      {{toExpandedRowKeys}}-->
    <el-table
        ref="theTable"
        :data="gridData"
        :width="550"
        :border="true"
        :row-class-name="rowClassNameIt"
        row-key="short"
        :expand-row-keys="toExpandedRowKeys"
        @sortChange="onSortChanged"
        @expandChange="onExpandChange">
      <!--        <el-table-column type="index" :index="(idx)=>indexing(idx,)">-->
      <!--            <el-table-column type="index" :index="indexing" sortable/>-->
      <!--            <template #default="theData">-->
      <!--                -->
      <!--            </template>-->
      <!--                <el-table-column type="index" :index="3" />-->
      <!--                <el-table-column width="80" property="rank" label="rank" sortable>-->
      <!--                  <template #default="theData">-->
      <!--                    @change="handleChange"-->
      <!--                    const handleChange = (value: number) => {-->
      <!--                      console.log(value)-->
      <!--                    }-->
      <!--                      <el-input-number-->
      <!--                          v-model="theData.row.rank"-->
      <!--                          :min="1"-->
      <!--                          :max="200"-->
      <!--                          size="small"-->
      <!--                          controls-position="right"-->
      <!--                      />-->
      <!--                  </template>-->
      <!--                </el-table-column>-->

      <el-table-column type="expand" ref="column1Ref" width="45">
        <template #default="theData">
<!--          <div v-if="theData.row.pos?.length>0" class="pwSubTable">-->
<!--            <RowPhraseWordSubTable v-model="theData.row.pos" :theParentTable="theTable"></RowPhraseWordSubTable>-->
<!--          </div>-->
<!--          <div v-if="theData.row.formsPos?.length>0" v-for="(formPos,idx) in theData.row.formsPos" class="pwSubTable">-->
<!--            {{formPos.form}}-->
            <RowPhraseWordSubTables v-if="theData.row.formsPos?.length>0" :theFormsPos="theData.row.formsPos"></RowPhraseWordSubTables>
<!--            <RowPhraseWordSubTable :theFormPos="formPos" :theParentTable="theTable"></RowPhraseWordSubTable>-->
<!--          </div>-->


<!--            <DraggableTest2></DraggableTest2>-->
        </template>
      </el-table-column>
      <el-table-column width="80" property="concept" label="@@" ref="column2Ref">
        <!--            <el-table-column property="concept" label="@@" ref="column2Ref">-->
        <!--            <el-table-column width="20%" property="concept" label="@@" ref="column2Ref">-->
        <!--            <el-button @click="console.log(`theData,`,gridData)">aaa</el-button>-->
      </el-table-column>
      <el-table-column width="250" property="pos" label="单词&短语">
        <!--            <el-table-column property="pos" label="单词&短语">-->
        <!--            <el-table-column width="25%" property="pos" label="单词&短语">-->
        <template #default="theData">
          <el-tag v-for="(thePos,idx) in theData.row.pos">{{ thePos.text }}</el-tag>
          <!--                    {{ theData.row.pos }}-->
        </template>
      </el-table-column>
      <el-table-column width="100" property="remarks" label="备注">
        <!--            <el-table-column property="remarks" label="备注">-->
        <!--            <el-table-column width="25%" property="remarks" label="备注">-->
        <template #default="theData">
          <el-tag v-for="(remark,idx) in theData.row.remarks">{{ remark }}</el-tag>
        </template>
      </el-table-column>
      <!--        <el-table-column width="156" property="rate" label="rate" sortable>-->
      <el-table-column width="100" property="rate" label="rate" sortable>
        <!--            <el-table-column property="rate" label="rate" sortable>-->
        <!--            <el-table-column width="25%" property="rate" label="rate" sortable>-->
        <!--                show-text-->
        <template #default="theData">
          <el-rate
              v-model="theData.row.rate"
              size="small"
              :texts="['瞄一眼', '随便看看', '普通', '次重要', '重要']"
              allow-half
              @click="console.log(`rateValue`,rateValue)"
          />

          <el-tooltip placement="right" effect="light">
            <el-icon>
              <InfoFilled/>
            </el-icon>

            <template #content>
              <div>{{ rateTexts[Math.ceil(theData.row.rate) - 1] }}</div>
            </template>

          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div style="float: right">
      <button class="my-button" @click="console.log(`theSortable,`,theRowSortable.toArray());
          gridData.push({
            id: 4,
            concept: '@@阻碍'+Math.random(),
            short:'za'+Math.random(),
            rank: 1,
            rate: 2,
            remarks: ['3', '4'],
            pos: []
        })">
        <el-icon>
          <Plus/>
        </el-icon>
      </button>
      <el-switch
          v-model="allSortableSw"
          inline-prompt
          active-text="Drag"
          :disabled="allSortableSwDisabled"
          inactive-text="noDrag"></el-switch>
      <!--          <button class="my-button">sortable?</button>-->
    </div>
  </div>
</template>

<style scoped>
:deep(.el-rate__text) {
  font-size: 10px;
}
</style>